const express = require('express');
const router = express.Router();
const CommunityPost = require('../mysql/collection/CommunityPost');
const PostCategory = require('../mysql/collection/PostCategory');

/**
 * @api {get} /admin/community/list 获取所有帖子
 * @apiName GetCommunityPostList
 * @apiGroup 社区帖子
 * @apiHeader {String} token  token
 * @apiParam {Number} [pageSize=10] 每页显示数量
 * @apiParam {Number} [pageNum=1] 当前页码
 * @apiSuccess {Object} data 分页数据
 * @apiSuccess {Object[]} data.list 帖子列表
 * @apiSuccess {String} data.list.postId 帖子ID
 * @apiSuccess {String} data.list.title 帖子标题
 * @apiSuccess {String} data.list.content 帖子内容
 * @apiSuccess {String} data.list.coverImage 封面图URL
 * @apiSuccess {Object} data.list.categoryId 关联分类信息
 * @apiSuccess {String} data.list.categoryId.categoryId 分类ID
 * @apiSuccess {String} data.list.categoryId.name 分类名称
 * @apiSuccess {Number} data.total 总记录数
 * @apiSuccess {Number} data.pageSize 每页显示数量
 * @apiSuccess {Number} data.pageNum 当前页码
 */
router.get('/list', async (req, res) => {
  try {
    const { pageSize = 10, pageNum = 1 } = req.query;
    const skip = (pageNum - 1) * pageSize;
    
    const [posts, total] = await Promise.all([
      CommunityPost.find({ flag: true }).skip(skip).limit(parseInt(pageSize)).populate('categoryId'),
      CommunityPost.countDocuments({ flag: true })
    ]);
    
    res.json({ 
      code: 200, 
      data: {
        list: posts,
        total,
        pageSize: parseInt(pageSize),
        pageNum: parseInt(pageNum)
      }
    });
  } catch (err) {
    res.status(500).json({ code: 500, message: err.message });
  }
});

/**
 * @api {post} /admin/community/create 创建帖子
 * @apiName CreateCommunityPost
 * @apiGroup 社区帖子
 * @apiHeader {String} token  token
 * @apiParam {String} title 帖子标题
 * @apiParam {String} content 帖子内容
 * @apiParam {String} categoryId 分类ID
 * @apiParam {String} [coverImage] 封面图URL
 * @apiParam {String} [videoUrl] 视频地址URL
 * @apiParam {String} authorId 作者ID
 */
router.post('/create', async (req, res) => {
  try {
    const { title, content, categoryId, coverImage, authorId } = req.body;
    if (!title || !content || !categoryId || !authorId) {
      return res.status(400).json({ code: 400, message: '标题、内容、分类ID和作者ID不能为空' });
    }
    
    const category = await PostCategory.findById(categoryId);
    if (!category) {
      return res.status(404).json({ code: 404, message: '分类不存在' });
    }
    
    const post = new CommunityPost({ 
      postId: Date.now().toString(),
      title,
      content,
      categoryId,
      coverImage,
      videoUrl: req.body.videoUrl,
      authorId
    });
    
    await post.save();
    res.json({ code: 200, data: post });
  } catch (err) {
    res.status(500).json({ code: 500, message: err.message });
  }
});

/**
 * @api {put} /admin/community/update/:id 更新帖子
 * @apiName UpdateCommunityPost
 * @apiGroup 社区帖子
 * @apiHeader {String} token  token
 * @apiParam {String} id 帖子ID
 * @apiParam {String} title 帖子标题
 * @apiParam {String} content 帖子内容
 * @apiParam {String} categoryId 分类ID
 * @apiParam {String} [coverImage] 封面图URL
 * @apiParam {String} [videoUrl] 视频地址URL
 */
router.put('/update/:id', async (req, res) => {
  try {
    const { title, content, categoryId, coverImage } = req.body;
    if (!title || !content || !categoryId) {
      return res.status(400).json({ code: 400, message: '标题、内容和分类ID不能为空' });
    }
    
    const category = await PostCategory.findById(categoryId);
    if (!category) {
      return res.status(404).json({ code: 404, message: '分类不存在' });
    }
    
    const post = await CommunityPost.findByIdAndUpdate(
      req.params.id,
      { title, content, categoryId, coverImage, videoUrl: req.body.videoUrl, updateTime: Date.now() },
      { new: true }
    );
    
    if (!post) {
      return res.status(404).json({ code: 404, message: '帖子不存在' });
    }
    
    res.json({ code: 200, data: post });
  } catch (err) {
    res.status(500).json({ code: 500, message: err.message });
  }
});

/**
 * @api {delete} /admin/community/delete/:id 删除帖子
 * @apiName DeleteCommunityPost
 * @apiGroup 社区帖子
 * @apiHeader {String} token  token
 * @apiParam {String} id 帖子ID
 */
router.delete('/delete/:id', async (req, res) => {
  try {
    const post = await CommunityPost.findByIdAndUpdate(
      req.params.id,
      { flag: false, updateTime: Date.now() },
      { new: true }
    );
    
    if (!post) {
      return res.status(404).json({ code: 404, message: '帖子不存在' });
    }
    
    res.json({ code: 200, data: post });
  } catch (err) {
    res.status(500).json({ code: 500, message: err.message });
  }
});

/**
 * @api {post} /admin/community/:id/comment 添加评论
 * @apiName AddComment
 * @apiGroup 社区帖子
 * @apiHeader {String} token  token
 * @apiParam {String} id 帖子ID
 * @apiParam {String} content 评论内容
 * @apiParam {String} authorId 评论作者ID
 */
router.post('/:id/comment', async (req, res) => {
  try {
    const { content, authorId } = req.body;
    if (!content || !authorId) {
      return res.status(400).json({ code: 400, message: '评论内容和作者ID不能为空' });
    }
    
    const post = await CommunityPost.findById(req.params.id);
    if (!post) {
      return res.status(404).json({ code: 404, message: '帖子不存在' });
    }
    
    const comment = {
      commentId: Date.now().toString()+Math.random().toString(36).substring(2, 4),
      content,
      authorId,
      createdAt: Date.now()
    };
    
    post.comments.push(comment);
    await post.save();
    
    res.json({ code: 200, data: comment });
  } catch (err) {
    res.status(500).json({ code: 500, message: err.message });
  }
});

/**
 * @api {get} /admin/community/:id/comments 获取帖子评论列表
 * @apiName GetPostComments
 * @apiGroup 社区帖子
 * @apiHeader {String} token  token
 * @apiParam {String} id 帖子ID
 * @apiParam {Number} [pageSize=10] 每页显示数量
 * @apiParam {Number} [pageNum=1] 当前页码
 */
router.get('/:id/comments', async (req, res) => {
  try {
    const { pageSize = 10, pageNum = 1 } = req.query;
    const skip = (pageNum - 1) * pageSize;
    
    const post = await CommunityPost.findById(req.params.id);
    if (!post) {
      return res.status(404).json({ code: 404, message: '帖子不存在' });
    }
    
    const comments = post.comments
      .filter(c => c.flag !== false)
      .slice(skip, skip + parseInt(pageSize));
    
    res.json({
      code: 200,
      data: {
        list: comments,
        total: post.comments.length,
        pageSize: parseInt(pageSize),
        pageNum: parseInt(pageNum)
      }
    });
  } catch (err) {
    res.status(500).json({ code: 500, message: err.message });
  }
});

/**
 * @api {delete} /admin/community/:id/comment/:commentId 删除评论
 * @apiName DeleteComment
 * @apiGroup 社区帖子
 * @apiHeader {String} token  token
 * @apiParam {String} id 帖子ID
 * @apiParam {String} commentId 评论ID
 */
router.delete('/:id/comment/:commentId', async (req, res) => {
  try {
    const post = await CommunityPost.findById(req.params.id);
    if (!post) {
      return res.status(404).json({ code: 404, message: '帖子不存在' });
    }
    
    const commentIndex = post.comments.findIndex(
      c => c.commentId === req.params.commentId
    );
    
    if (commentIndex === -1) {
      return res.status(404).json({ code: 404, message: '评论不存在' });
    }
    
    post.comments[commentIndex].flag = false;
    await post.save();
    
    res.json({ code: 200, data: post.comments[commentIndex] });
  } catch (err) {
    res.status(500).json({ code: 500, message: err.message });
  }
});

module.exports = router;